package cn.yunsenlin.formula.cloud.responsibility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 方法责任链
 */
public abstract class ResponseResponsibilityHandler {
    private static Logger logger = LoggerFactory.getLogger(ResponseResponsibilityHandler.class);

    /**
     * 当前处理器进行操作
     *
     * @param object   业务参数
     * @param response 相应
     * @return 返回值依据业务而定
     */
    protected abstract Object doHandler(HttpServletResponse response, Object object);

    /**
     * 是否会进行下一个处理器操作
     *
     * @param response 相应
     * @param object   业务参数
     * @return 是否会进行下一个处理器操作
     */
    protected abstract boolean continueAble(HttpServletResponse response, Object object);

    /**
     * 主方法，用于启动责任链
     *
     * @param list     责任链
     * @param response 相应
     * @param objects  业务参数数组
     * @return 责任链控制的返回值
     */
    public static Object start(List<ResponseResponsibilityHandler> list
            , HttpServletResponse response, Object... objects) {
        Object result = null;
        int objSize = objects.length;
        for (int i = 0; i < list.size(); i++) {
            String className = list.get(i).getClass().getSimpleName();
            className = className.isEmpty() ? "[inner handler]" : className;
            if (!list.get(i).continueAble(response, i < objSize ? objects[i] : null)) {
                logger.error(className + " service checked continueAble fail!");
                break;
            }
            logger.debug(className + " service checked passed! ");
            logger.debug("by:" + Thread.currentThread().getStackTrace()[3].getClassName() +
                    ":" + Thread.currentThread().getStackTrace()[3].getMethodName());
            result = list.get(i).doHandler(response, i < objSize ? objects[i] : null);
        }
        return result;
    }
}
